<template>
	<view class="outbound-container">
		<!-- 搜索栏及两侧按钮 -->
		<view class="search-row">
			<view class="search-box-flex">
				<u-search
					v-model="searchKeyword"
					placeholder="搜索订单号、商品名称、客户"
					:show-action="false"
					:clearabled="true"
					@search="onSearch"
					@custom="onSearch"
					@clear="onClear"
				></u-search>
			</view>
			<u-button class="icon-btn" type="success" size="mini" @click="onScanOutbound" :custom-style="{padding: '0 16rpx', marginRight: '10rpx'}">
				<u-icon name="scan" size="24" color="#333"></u-icon>
			</u-button>
		</view>

		<!-- tabs页签 -->
		<view class="tabs-section">
			<u-tabs
				:list="tabList"
				v-model:current="currentTab"
				@change="onTabChange"
				lineColor="#2979ff"
				:activeStyle="{color: '#2979ff', fontWeight: 'bold'}"
				:inactiveStyle="{color: '#666'}"
			></u-tabs>
		</view>

		<!-- 列表区域 -->
		<view class="list-section">
			<view class="order-list">
				<view 
					class="order-item" 
					v-for="(item, index) in orderList" 
					:key="item.id"
					@click="onOrderClick(item)"
				>
					<view class="order-header">
						<view class="order-info">
							<text class="order-number">{{ item.orderNo }}</text>
							<u-tag 
								:text="getStatusText(item.status)" 
								:type="getStatusType(item.status)"
								size="mini"
							></u-tag>
						</view>
						<view class="order-date">
							<text class="date-text">{{ formatDate(item.createTime) }}</text>
						</view>
					</view>
					<view class="order-content">
						<view class="supplier-info">
							<u-icon name="account" size="16" color="#666"></u-icon>
							<text class="supplier-text">{{ item.customerName }}</text>
						</view>
						<view class="goods-info">
							<text class="goods-text">{{ item.goodsCount }}种商品</text>
							<text class="quantity-text">共{{ item.totalQuantity }}件</text>
						</view>
						<view class="box-info">
							<view class="box-meta">
								<text class="box-text">尺寸: {{ item.length || '--' }} x {{ item.width || '--' }} x {{ item.height || '--' }} CM</text>
								<text class="box-text">体积: {{ item.volume || '--' }} CBM</text>
								<text class="box-text">重量: {{ item.weight || '--' }} KG</text>
							</view>
						</view>
					</view>
					<view class="order-footer">
						<view class="progress-info">
							<text class="progress-text">出库进度: {{ item.outboundQuantity }}/{{ item.totalQuantity }}</text>
							<u-line-progress 
								:percentage="getProgressPercentage(item)" 
								:show-text="false"
								height="6"
							></u-line-progress>
						</view>
						<view class="action-buttons">
							<u-button 
								v-if="item.status === 'pending'"
								type="primary" 
								size="mini" 
								@click.stop="onStartOutbound(item)"
							>
								开始出库
							</u-button>
							<u-button 
								v-if="item.status === 'processing'"
								type="success" 
								size="mini" 
								@click.stop="onContinueOutbound(item)"
							>
								继续出库
							</u-button>
							<u-button 
								v-if="item.status === 'completed'"
								type="info" 
								size="mini" 
								@click.stop="onViewDetail(item)"
							>
								查看详情
							</u-button>
						</view>
					</view>
				</view>
			</view>
			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore">
				<u-loadmore 
					:status="loadMoreStatus" 
					@loadmore="onLoadMore"
				></u-loadmore>
			</view>
			<!-- 空状态 -->
			<view class="empty-state" v-if="orderList.length === 0 && !loading">
				<u-empty 
					text="暂无出库订单" 
					mode="list"
				></u-empty>
			</view>
		</view>

		<!-- 筛选弹窗 -->
		<u-popup 
			v-model="showFilterModal" 
			mode="bottom" 
			:closeable="true"
			:round="10"
		>
			<view class="filter-modal">
				<view class="filter-header">
					<text class="filter-title">筛选条件</text>
				</view>
				<view class="filter-content">
					<view class="filter-item">
						<text class="filter-label">订单状态</text>
						<u-radio-group v-model="filterStatus" @change="onFilterChange">
							<u-radio 
								v-for="status in statusOptions" 
								:key="status.value"
								:name="status.value"
								:label="status.label"
							></u-radio>
						</u-radio-group>
					</view>
					<view class="filter-item">
						<text class="filter-label">时间范围</text>
						<u-datetime-picker 
							v-model="filterDateRange" 
							mode="range"
							@confirm="onDateRangeChange"
						></u-datetime-picker>
					</view>
				</view>
				<view class="filter-actions">
					<u-button @click="onResetFilter">重置</u-button>
					<u-button type="primary" @click="onApplyFilter">确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			searchKeyword: '',
			showFilterModal: false,
			filterStatus: '',
			filterDateRange: [],
			orderList: [],
			loading: false,
			hasMore: true,
			loadMoreStatus: 'loadmore',
			page: 1,
			pageSize: 10,
			totalCount: 0,
			pendingCount: 0,
			completedCount: 0,
			// tabs相关
			tabList: [
				{ name: '全部(0)', value: '' },
				{ name: '待出库(0)', value: 'pending' },
				{ name: '已出库(0)', value: 'completed' }
			],
			currentTab: 0,
			statusOptions: [
				{ label: '全部', value: '' },
				{ label: '待出库', value: 'pending' },
				{ label: '出库中', value: 'processing' },
				{ label: '已出库', value: 'completed' },
				{ label: '已取消', value: 'cancelled' }
			]
		}
	},
	onLoad() {
		this.loadOrderList()
		this.loadStatistics()
	},
	onPullDownRefresh() {
		this.refreshData()
	},
	onReachBottom() {
		if (this.hasMore && this.loadMoreStatus === 'loadmore') {
			this.onLoadMore()
		}
	},
	methods: {
		async loadOrderList(isLoadMore = false) {
			if (this.loading) return
			this.loading = true
			if (!isLoadMore) {
				this.page = 1
				this.orderList = []
			}
			try {
				const params = {
					page: this.page,
					pageSize: this.pageSize,
					keyword: this.searchKeyword,
					status: this.filterStatus,
					startDate: this.filterDateRange[0] || '',
					endDate: this.filterDateRange[1] || ''
				}
				const mockData = this.getMockData(params)
				if (isLoadMore) {
					this.orderList = [...this.orderList, ...mockData.list]
				} else {
					this.orderList = mockData.list
				}
				this.hasMore = mockData.hasMore
				this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore'
				if (isLoadMore) {
					this.page++
				}
			} catch (error) {
				console.error('加载订单列表失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				uni.stopPullDownRefresh()
			}
		},
		async loadStatistics() {
			try {
				this.totalCount = 120
				this.pendingCount = 18
				this.completedCount = 102
				this.tabList = [
					{ name: `待出库(${this.pendingCount})`, value: 'pending' },
					{ name: `已出库(${this.completedCount})`, value: 'completed' }
				]
			} catch (error) {
				console.error('加载统计数据失败:', error)
			}
		},
		getMockData(params) {
			const mockList = []
			const startIndex = (params.page - 1) * params.pageSize
			for (let i = 0; i < params.pageSize; i++) {
				const index = startIndex + i
				if (index >= 120) break
				const statuses = ['pending', 'processing', 'completed', 'cancelled']
				const status = statuses[Math.floor(Math.random() * statuses.length)]
				const order = {
					id: `OUT${String(index + 1).padStart(6, '0')}`,
					orderNo: `OUT${String(index + 1).padStart(6, '0')}`,
					status: status,
					customerName: `客户${index + 1}`,
					goodsCount: Math.floor(Math.random() * 10) + 1,
					totalQuantity: Math.floor(Math.random() * 100) + 10,
					outboundQuantity: status === 'completed' ? Math.floor(Math.random() * 100) + 10 : 
									status === 'processing' ? Math.floor(Math.random() * 50) + 5 : 0,
					createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
					length: Math.floor(Math.random() * 60) + 20,
					width: Math.floor(Math.random() * 40) + 20,
					height: Math.floor(Math.random() * 40) + 20,
					volume: (Math.random() * 1.5 + 0.1).toFixed(2),
					weight: (Math.random() * 30 + 1).toFixed(1)
				}
				if (params.keyword && !order.orderNo.includes(params.keyword) && 
					!order.customerName.includes(params.keyword)) {
					continue
				}
				if (params.status && order.status !== params.status) {
					continue
				}
				mockList.push(order)
			}
			return {
				list: mockList,
				hasMore: startIndex + params.pageSize < 120
			}
		},
		onSearch() {
			this.loadOrderList()
		},
		onClear() {
			this.searchKeyword = ''
			this.loadOrderList()
		},
		onRefresh() {
			this.refreshData()
		},
		refreshData() {
			this.loadOrderList()
			this.loadStatistics()
		},
		onLoadMore() {
			if (this.hasMore && !this.loading) {
				this.loadMoreStatus = 'loading'
				this.loadOrderList(true)
			}
		},
		onFilterChange() {},
		onDateRangeChange(e) {
			this.filterDateRange = e
		},
		onResetFilter() {
			this.filterStatus = ''
			this.filterDateRange = []
		},
		onApplyFilter() {
			this.showFilterModal = false
			this.loadOrderList()
		},
		onAddOutbound() {
			uni.navigateTo({ url: '/pages/outbound/add/add' })
		},
		onScanOutbound() {
			uni.scanCode({
				success: (res) => {
					uni.showToast({ title: '扫码成功', icon: 'success' })
				},
				fail: (err) => {
					uni.showToast({ title: '扫码失败', icon: 'none' })
				}
			})
		},
		onOrderClick(item) {
			uni.navigateTo({ url: `/pages/outbound/detail/detail?id=${item.id}` })
		},
		onStartOutbound(item) {
			uni.navigateTo({ url: `/pages/outbound/process/process?id=${item.id}` })
		},
		onContinueOutbound(item) {
			uni.navigateTo({ url: `/pages/outbound/process/process?id=${item.id}` })
		},
		onViewDetail(item) {
			uni.navigateTo({ url: `/pages/outbound/detail/detail?id=${item.id}` })
		},
		getStatusText(status) {
			const statusMap = {
				'pending': '待出库',
				'processing': '出库中',
				'completed': '已出库',
				'cancelled': '已取消'
			}
			return statusMap[status] || '未知'
		},
		getStatusType(status) {
			const typeMap = {
				'pending': 'warning',
				'processing': 'primary',
				'completed': 'success',
				'cancelled': 'error'
			}
			return typeMap[status] || 'info'
		},
		getProgressPercentage(item) {
			if (item.totalQuantity === 0) return 0
			return Math.round((item.outboundQuantity / item.totalQuantity) * 100)
		},
		formatDate(dateString) {
			const date = new Date(dateString)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
		},
		onTabChange(index) {
			this.currentTab = index;
			this.filterStatus = this.tabList[index].value;
			this.loadOrderList();
		}
	}
}
</script>

<style lang="scss" scoped>
.outbound-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 20rpx;
}
.search-row {
	display: flex;
	align-items: center;
	background: #fff;
	padding: 20rpx 20rpx 0 20rpx;
	margin-bottom: 10rpx;
	.search-box-flex {
		flex: 1;
	}
	.icon-btn {
		border-radius: 50%;
		padding: 0 !important;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: transparent !important;
		border: none !important;
		box-shadow: none !important;
	}
}
.tabs-section {
	background: #fff;
	padding: 0 20rpx;
	margin-bottom: 20rpx;
}
.list-section {
	background-color: #ffffff;
	margin: 0 20rpx;
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	.order-list {
		.order-item {
			background-color: #f8f9fa;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;
			border: 1rpx solid #e9ecef;
			.order-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 25rpx;
				.order-info {
					display: flex;
					align-items: center;
					.order-number {
						font-size: 32rpx;
						font-weight: bold;
						color: #333333;
						margin-right: 25rpx;
					}
				}
				.order-date {
					.date-text {
						font-size: 26rpx;
						color: #999999;
					}
				}
			}
			.order-content {
				margin-bottom: 25rpx;
				.supplier-info {
					display: flex;
					align-items: center;
					margin-bottom: 15rpx;
					.supplier-text {
						font-size: 30rpx;
						color: #666666;
						margin-left: 15rpx;
					}
				}
				.goods-info {
					display: flex;
					justify-content: space-between;
					.goods-text, .quantity-text {
						font-size: 26rpx;
						color: #666666;
					}
				}
				.box-info {
					display: flex;
					align-items: flex-start;
					margin-top: 12rpx;
					margin-bottom: 4rpx;
					.box-icon {
						margin-top: 2rpx;
					}
					.box-meta {
						display: flex;
						flex-wrap: wrap;
						gap: 24rpx;
					}
					.box-text {
						font-size: 24rpx;
						color: #888;
						line-height: 36rpx;
					}
				}
			}
			.order-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				.progress-info {
					flex: 1;
					margin-right: 30rpx;
					.progress-text {
						font-size: 26rpx;
						color: #666666;
						margin-bottom: 15rpx;
						display: block;
					}
				}
				.action-buttons {
					display: flex;
					gap: 15rpx;
					::v-deep .u-button {
						min-width: 120rpx;
						height: 60rpx;
						font-size: 26rpx;
					}
				}
			}
		}
	}
}
.load-more {
	margin-top: 40rpx;
}
.empty-state {
	margin-top: 120rpx;
}
.filter-modal {
	padding: 50rpx 40rpx;
	.filter-header {
		margin-bottom: 50rpx;
		.filter-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
		}
	}
	.filter-content {
		.filter-item {
			margin-bottom: 50rpx;
			.filter-label {
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 25rpx;
				display: block;
			}
		}
	}
	.filter-actions {
		display: flex;
		gap: 25rpx;
		margin-top: 50rpx;
		::v-deep .u-button {
			flex: 1;
			height: 80rpx;
			font-size: 30rpx;
		}
	}
}
/* #ifdef APP-PLUS */
.search-row {
	padding: 40rpx 20rpx;
}
.list-section {
	padding: 50rpx 30rpx;
}
.order-list .order-item {
	padding: 35rpx;
}
.filter-modal {
	padding: 60rpx 40rpx;
}
/* #endif */
@media screen and (max-width: 750rpx) {
	.list-section {
		padding: 30rpx 20rpx;
	}
	.order-list .order-item {
		padding: 25rpx;
	}
}
</style> 